import os
import sys
import getopt
import subprocess


class Cfg(object):
    usage = """
        python3 ss_ominstall.py -x xml -u user -p pkg
    """

    user = None
    package_path = None
    xml = None
    
    envfile = ''

    @staticmethod
    def init():
        argv = sys.argv[1:]
        short_options = 'x:u:p'
        long_options = ['xml=', 'user=', 'package=']
        opts, args = getopt.getopt(argv, short_options, long_options)
        if len(args) > 1:
            print('unknown param ' + args[0])
            exit(1)
        for opt, arg in opts:
            if opt in ['-x', '--xml']:
                Cfg.xml = arg
            elif opt in ['-u', '--user']:
                Cfg.user = arg
            elif opt in ['-p', '--package']:
                Cfg.package_path = arg
                
            else:
                assert False
        if Cfg.xml is None or Cfg.user is None:
            print('缺少参数。\n', Cfg.usage)
            exit(1)
        
        Cfg.envfile = os.path.join('home', Cfg.user, 'clsuter.source')

    @staticmethod
    def print_info():
        print(f'Install infomations:')
        print(f'    user: {Cfg.user}')
        print(f'    package_path: {Cfg.package_path}')
        print(f'    xml: {Cfg.xml}')
        print(f'                  ')
        print(f'    envfile: {Cfg.envfile}')



def check_package():
    pass


def check_env():
    pass


def preinstall():
    script_path = os.path.join(Cfg.package_path, 'script')
    cmd = f'cd {script_path} && ./gs_preinstall -U {Cfg.user} -G {Cfg.user} -X {Cfg.xml} --sep-env-file={Cfg.envfile}'
    print('预安装', cmd)
    process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
    
    stdout, stderr = process.communicate(input=b'yes\nopenGauss1#2_3$00\nyes\nGauss@123\n')
    if process.returncode != 0:
        print(stdout.decode('utf-8'))
        print('命令执行遇到错误。', stderr.decode('utf-8'))
        exit(1)
        

def install():
    cmd = f"su - {Cfg.user} -c 'source {Cfg.envfile} && gs_install -X {Cfg.xml}'"
    print('开始安装', cmd)
    process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

    password = b"Gauss@123\n"
    process.stdin.write(password)
    process.stdin.flush()
    process.stdin.write(password)
    process.stdin.flush()

    stdout, stderr = process.communicate()

    if process.returncode != 0:
        print(stdout.decode('utf-8'))
        print('命令执行遇到错误。', stderr.decode('utf-8'))
        exit(1)





if __name__ == '__main__':
    Cfg.init()
    Cfg.print_info()
    
    check_package()
    check_env()
    
    preinstall()
    install()
    
    print('安装完成.')

